﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace NhWeather.Helpers;

public static class TextBoxHelper
{
    public static readonly DependencyProperty WatermarkProperty =
        DependencyProperty.RegisterAttached("Watermark", typeof(string), typeof(TextBoxHelper), new PropertyMetadata(string.Empty, OnWatermarkChanged));

    public static string GetWatermark(DependencyObject obj)
    {
        return (string)obj.GetValue(WatermarkProperty);
    }

    public static void SetWatermark(DependencyObject obj, string value)
    {
        obj.SetValue(WatermarkProperty, value);
    }

    private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is TextBox textBox)
        {
            textBox.Loaded += (sender, args) => ShowWatermark(textBox);
            textBox.GotFocus += (sender, args) => HideWatermark(textBox);
            textBox.LostFocus += (sender, args) => ShowWatermark(textBox);
        }
    }

    private static void ShowWatermark(TextBox textBox)
    {
        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.Foreground = Brushes.Gray;
            textBox.Text = GetWatermark(textBox);
        }
    }

    private static void HideWatermark(TextBox textBox)
    {
        if (textBox.Foreground == Brushes.Gray)
        {
            textBox.Foreground = Brushes.Black;
            textBox.Text = string.Empty;
        }
    }
}